package service

import (
	"github.com/gin-gonic/gin"
	"monment/basic/config"
	"monment/handler/model"
	"monment/handler/request"
	"net/http"
)

func AddLike(c *gin.Context) {
	var form request.AddLike
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}
	var like model.Like
	if err := like.IsLike(config.DB, form.UserId, form.PostId); err == nil {
		if like.Count == 0 {
			config.DB.Model(&like).Select("count").Update("count", 1)
			c.JSON(http.StatusOK, gin.H{
				"code": 200,
				"msg":  "点赞成功",
			})
			return
		}
		config.DB.Model(&like).Select("count").Update("count", 0)
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 200,
			"msg":  "已取消点赞",
		})
		return
	}
	like = model.Like{
		UserId: form.UserId,
		PostId: form.PostId,
		Count:  1,
	}
	err := like.AddLike(config.DB)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "点赞失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "点赞成功",
	})
	return
}
